package linc.cool.framework.register;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import linc.cool.framework.URL;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author yqlin
 * @date 2022/3/11 3:06 下午
 * @description 可以使用redis, zookeeper来取代文件当注册中心 为了避免每次都要进行网络IO,可以在消费者端进行缓存注册信息
 */
public class RemoteMapRegister {
    private static Map<String, List<URL>> REGISTER = Maps.newHashMap();

    public static void register(String interfaceName, URL url) {
        List<URL> list = REGISTER.get(interfaceName);
        if (CollectionUtils.isEmpty(list)) {
            list = Lists.newArrayList();
        }
        list.add(url);
        REGISTER.put(interfaceName, list);
        saveFile();
    }

    public static List<URL> get(String interfaceName) {
        REGISTER = getFile();
        return REGISTER.get(interfaceName);
    }

    private static void saveFile() {
        try {
            File file = new File(System.getProperties().getProperty("user.dir") + "/tmp.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            var fileOutputStream = new FileOutputStream(file);
            var objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(REGISTER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @SuppressWarnings("unchecked")
    public static Map<String, List<URL>> getFile() {
        try {
            File file = new File(System.getProperties().getProperty("user.dir") + "/tmp.txt");
            var fileInputStream = new FileInputStream(file);
            var objectInputStream = new ObjectInputStream(fileInputStream);
            return (Map<String, List<URL>>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return Maps.newHashMap();
    }
}
